import RequestModel from './request'
const Config = require('@/config/base_config');
const Storage = require('@/utils/storage');
const Util = require('@/utils/util.js')
const {
  checkTokenExpiration
} = require('@/utils/auth');
console.log(RequestModel);
const API_DOMAIN = Config.API_HOST;
/**
 * 刷新 Token
 */
const refreshAccessToken = () => {
  const refreshToken = Storage.get('refresh_token');
  return new Promise((resolve, reject) => {
    wx.request({
      url: `${API_DOMAIN}/api/auth/refresh`,
      method: 'POST',
      data: {
        refresh_token: refreshToken
      }, // 传递 refreshToken
      success: (res) => {
        console.log(res)
        if (res.data.code === 200) {
          let access_expires_in = Util.timeToSeconds(res.data.access_expires_in);
          Storage.set('access_token', res.data.access_token, access_expires_in || 5 * 60);
          resolve(res.data.access_token);
        } else {
          reject(new Error('刷新 Token 失败'));
        }
      },
      fail: (err) => reject(err),
    });
  });
};

const Http = new RequestModel();
// 示例拦截器配置
Http.addRequestInterceptor(async (config) => {
    console.log(config)
    if (!config.skipAuth) {
      const refreshToken = Storage.get('refresh_token');
      let accessToken = Storage.get('access_token');
      if (!refreshToken) { // --未登录/登录过期重新登录
        Http.redirectToLogin();
        throw {
          code: 401,
          message: '登录已过期，请重新登录',
          config: config
        };
      }
      if (!accessToken) { // --请求接口的token过期，刷新token
        accessToken = await refreshAccessToken();
        throw {
          code: 401,
          message: 'token已过期，请重新获取',
          config: config
        };
      }
      if (checkTokenExpiration(accessToken)) {
        config._needsTokenRefresh = true;
      }
      console.log(accessToken)
      console.log(config)
      // 确保header存在
      if (!config.header) {
        config.header = {};
      }
      if (accessToken) {
        config.header.Authorization = `Bearer ${accessToken}`;
      }
    }
    console.log('请求拦截器 - 请求前', config);
    return config;
  },
  (error) => {
    return Promise.reject(error);
  });

Http.addResponseInterceptor(
  (response) => {
    console.log('响应拦截器 - 响应后', response);
    wx.hideLoading()
    return response;
  },
  (error) => {
    if (error.statusCode === 403) {
      wx.showModal({
        title: '权限不足',
        content: '当前账号没有权限访问此功能',
        showCancel: false
      });
    }
    return Promise.reject(error);
  }
);
export default Http;
//  module.exports= Http;